package com.fzy.modules.goods.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.fzy.core.common.IDUtils;
import com.fzy.modules.goods.dao.GoodsCategoryDao;
import com.fzy.modules.goods.entity.GoodsCategory;

/**
 * 商品分类操作
 * */
@Service
public class GoodsCategoryService  {
    @Autowired
    GoodsCategoryDao goodsCategoryDao;
    /**
     * 查询分类是否有子级分类
     * */
    public Integer isChildrenCategory(String id){
        return goodsCategoryDao.isChildrenCategory(id);
    }
    /**
     * 查询所有分类(返回树形结构)
     */
    public List<GoodsCategory> findAllList(){
    	List<GoodsCategory> categorys = goodsCategoryDao.findAllList();
    	List<GoodsCategory> result=new ArrayList<GoodsCategory>();
    	  Iterator<GoodsCategory> iterator = categorys.iterator(); 
          while  (iterator.hasNext()){ 
        	  GoodsCategory temp=  iterator.next();
              if  ( StringUtils.isEmpty( temp.getParentId())) 
            	  result.add(temp);
          } 
    	return categoryTree(categorys,result);
    }
    /**
     * 查询所有分类（集合结构）
     */
    public List<GoodsCategory> findAll(){
        return goodsCategoryDao.findAllList();
    }
    /**
     * 递归生成分类树
     * @param categorys
     * @param categoryTree
     * @return
     */
    private List<GoodsCategory> categoryTree(List<GoodsCategory> categorys,List<GoodsCategory> categoryTree){
    	
    	for(int i=0;i<categoryTree.size();i++){//循环父节点
    		List<GoodsCategory> tempChild=new ArrayList<GoodsCategory>();//新建一个临时子节点list
    		 Iterator<GoodsCategory> tempIterator=categorys.iterator();
    		while(tempIterator.hasNext()){//循环查询结果
    			GoodsCategory temp=tempIterator.next();
    			if(categoryTree.get(i).getId().equals(temp.getParentId())){//如果当前父节点id等于循环到的结点parentid
    				tempChild.add(temp);//存入临时结点
    			}
    		}
    		categoryTree(categorys,tempChild);
    		categoryTree.get(i).setGoodsCategorys(tempChild);//第一级子节点查找完成存放到相应结点中
    	}
    	return categoryTree;
    }
    /**
     * 添加分类
     */
    public Integer save(GoodsCategory goodsCategory){
       // String uuid= UUID.randomUUID().toString().toUpperCase();
        goodsCategory.setId(IDUtils.genItemId());
        if(StringUtils.isEmpty(goodsCategory.getCompanyId())){
            goodsCategory.setCompanyId("4D74E1E4-A129-11E4-9B6A-782BCBD7746B");
        }
        if(StringUtils.isEmpty(goodsCategory.getDataOrg())){
            goodsCategory.setDataOrg("01010001");
        }
        return goodsCategoryDao.save(goodsCategory);}
    /**
     * 修改分类
     */
    public Integer update(GoodsCategory goodsCategory){return goodsCategoryDao.update(goodsCategory);}
    /**
     * 删除分类
     */
    public Integer delete(String id){return goodsCategoryDao.delete(id);}
}
